let util = require('../../utils/util')
let p

Page({

    data: {
        icon: 'waiting',
        color: '#0091ea',
        statusText: '确认中',
        timeout: false,
        checking: false,
        success: false,
		reCheck: false
    },

	temp: {
		orderId: '',
		retryNum: 0,
		retryTimer: null
	},

    onLoad: function(params) {
        p = this
		p.temp.orderId = params.orderId
        wx.showNavigationBarLoading()
		p.checkOrderPayStatus(p.temp.orderId)
    },

	//用户自己关页面停止延时跳转
	onHide: () => {
		clearTimeout(p.temp.retryTimer)
	},

    showSuccess: () => {
        p.setData({
            success: true,
            icon: 'success',
            color: '',
            statusText: '支付成功'
        })
        util.globalData('payedTemp', true)
        wx.setNavigationBarTitle({
            title: '支付成功',
        })
    },

	checkOrderPayStatus: (orderId) => {
		p.temp.retryNum = 0
        p.temp.retryTimer = setInterval(() => {
			p.temp.retryNum++
			if (p.temp.retryNum == 10) {
				clearInterval(p.temp.retryTimer)
				wx.hideNavigationBarLoading()
				p.setData({
					icon: 'info',
					statusText: '确认失败',
					reCheck: true
				})
			}
            p.getUserPayStatus(orderId, (userPayed) => {
                if (userPayed) {
					clearInterval(p.temp.retryTimer)
                    wx.hideNavigationBarLoading()
                    p.showSuccess() 
                }
            })
        }, 1500)
    },

	reCheckOrderStatus: () => {
		p.setData({
			icon: 'waiting',
			color: '#0091ea',
			statusText: '确认中',
			reCheck: false
		})
		p.onLoad({ orderId: p.temp.orderId })
	},

    getUserPayStatus: (orderId, callback) => {
        if (p.data.checking) {
            return
        }
        p.setData({
            checking: true
        })
        util.request({
            method: 'get',
			uri: `order/${orderId}/check/pay`,
			data: {
				session: util.globalData('session')
			},
            success: (data) => {
                callback(data)
                p.setData({
                    checking: false
                })
            },
            fail: (err) => {
                console.error(err)
                p.setData({
                    checking: false
                })
            }
        })
    },

	endPay: () => {
		wx.navigateBack({
			delta: 3
		})
	}

})